<template>
  <view class="shop-container mo-container">
    <!-- 顶部导航 -->
    <view class="header bg-white">
      <view class="container uni-py-7">
        <view class="d-flex justify-content-between align-items-center uni-px-5">
          <view >
            <text class="animate__animated animate__fadeInDown uni-error fs-6">文创商城</text>
          </view>
          <view class="d-flex align-items-center ">
            <!-- 发布商品按钮 - 仅商家可见 -->
            <navigator v-if="userStore && userStore.userInfo && userStore.userInfo.role === 2" url="/pages/other/shop/publish" class="uni-mr-3">
              <button size="large" class="bg-primary-new">
                <text class="bi bi-plus-circle me-2 text-white">发布商品</text>
              </button>
            </navigator>
            <navigator url="/pages/shop/merchant-join" class="uni-mr-3">
              <button size="large" class="bg-primary-new">
                <text class="bi bi-shop me-2 text-white">商家入驻</text>
              </button>
            </navigator>
            <navigator url="/pages/other/cart/index" class=" uni-mr-3">
              <button  size="large" class="bg-primary-new ">
                <text class="bi bi-cart-plus me-2 text-white ">购物车</text>
              </button>
            </navigator>
          </view>
        </view>
      </view>
    </view>
    <view>
      <view @tap="navigateToForum">
        <cover-image
          :src="url('toy', '0', 'png')"
          class="img-fluid"
          alt=""
        ></cover-image>
      </view>
    </view>

    <view class="search-section px-3 py-2 bg-white">
      <uni-search-bar
        v-model="searchKey"
        placeholder="搜索商品"
        radius="100"
        cancelButton="none"
        @input="onSearch"
      />

      <view class="search-suggestions" v-if="searchKey && suggestions.length">
        <view
          class="suggestion-item p-2 border-bottom"
          v-for="item in suggestions"
          :key="item.id"
          @tap="selectSuggestion(item)"
        >
          <text class="bi bi-search me-2"></text>
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>

    <scroll-view
      scroll-x
      class="category-tabs bg-white uni-my-3"
      show-scrollbar="false"
    >
      <view class="tab-list px-3">
        <uni-group>
          <uni-segmented-control
            :current="
              categories.findIndex((cat) => cat.value === activeCategory)
            "
            :values="categories.map((cat) => cat.label)"
            @clickItem="onCategoryChange"
            styleType="button"
            activeColor="#6c8380"
          />
        </uni-group>
      </view>
    </scroll-view>

    <!-- 商品列表 -->
    <scroll-view scroll-y class="product-list" @scrolltolower="loadMore">
      <view class="container">
        <view class="product-grid">
          <view
            v-for="(product,index) in filteredProducts"
            :key="product.id"
            class="product-item"
            @tap="navigateToDetail(product.id)"
          >
            <view class="product-card">
              <view class="product-image">
                <cover-image
                  :src="url('sp', product.id-1, 'png')"
                  mode="aspectFill"
                ></cover-image>
              </view>
              <view class="product-info">
                <view class="product-header">
                  <text class="product-name">{{ product.name }}</text>
                  <uni-tag text="新品" type="error" v-if="product.isNew" />
                </view>
                <text class="uni-error fs-4">¥</text>
                <text class="uni-error fs-4">{{ product.price.toFixed(2) }} </text>
                <view class="d-flex justify-content-between align-items-center">
                  <text class="sales-info">已售 {{ product.sales }}+</text>
                  <!-- <button
                    class="rounded-circle uni-mr-2" 
                    type="warn"
                    @tap.stop="showSpecsDialog(product)"
                  >
                    <text class="bi bi-cart-plus"></text>
                  </button> -->
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <uni-popup ref="specsPopup" type="bottom" background-color="#fff">
      <view class="">
        <view class="specs-header uni-pa-5 border-bottom">
          <view class="d-flex justify-content-between">
            <cover-image
              :src="url('s', selectedProduct?.image, 'png')"
              class="specs-image me-3"
              mode="aspectFill"
            ></cover-image>
            <view class="flex-grow-1">
              <view class="fs-3 uni-my-2">{{ selectedProduct?.name }}</view>
              <view class="text-danger"
                >¥{{ selectedProduct?.price?.toFixed(2) }}</view
              >
            </view>
            <view> <button
              type="error"
              size="mini"
              class="close-btn"
              @click="closeSpecsDialog"
            >
              <text class=" bi-x fs-4"></text>
            </button> </view>
           
          </view>
        </view>

        <view class="specs-body uni-pa-5">

          <view class="specs-section uni-my-4" v-if="currentSpecs.length">
            <text class="d-block uni-my-2">选择规格</text>
            <uni-group>
              <uni-segmented-control
                :current="selectedSpecIndex"
                :values="currentSpecs.map((s) => s.label)"
                @clickItem="onSpecChange"
                styleType="button"
                activeColor="#981f23"
              />
            </uni-group>
          </view>


          <view class="quantity-section">
            <text class="d-block uni-my-2">数量</text>
            <uni-number-box v-model="quantity" :min="1" :max="99" />
          </view>
        </view>

        <view class="uni-pa-5 border-top">
          <button type="warn" class=" w-100" @tap="addToCart">
            加入购物车
          </button>
        </view>
      </view>
    </uni-popup>

   
  </view>
</template>

<script setup>
import { ref,reactive, computed } from "vue";
import { useCounterStore } from "@/stores/counter";
import { useCartStore } from "@/stores/cartStore";
import { useUserStore } from "@/stores/userStore";


const turnNum = ref(5);
const store = useCounterStore();
const userStore = useUserStore();
const url = $url;
const specsPopup = ref(null);
const toolbarPopup = ref(null);
const isDarkMode = ref(false);

const searchKey = ref("");
const activeCategory = ref("all");

const categories = [
  { label: "全部", value: "all" },
  { label: "文具", value: "stationery" },
  { label: "饰品", value: "accessories" },
  { label: "服饰", value: "clothing" },
  { label: "生活", value: "daily" },
  { label: "收藏", value: "collection" }
];

// 商品数据
const products = [
  {
    id: 1,
    name: "墨枢笔记本",
    description: "系列灵感源自中国古代物理实验场景，将传统文化的深厚底蕴与现代科学探索精神完美融合。每一页都仿佛带您穿越时空，亲历古代智慧的结晶。",
    price: 39.9,
    image: "notebook",
    category: "stationery",
    sales: 128,
    isNew: true
  },
  {
    id: 2,
    name: "墨枢项链系列",
    description: "灵感源自中国古代伟大的物理发明，将千年智慧与现代设计完美结合。每一款吊坠都细致刻画了古代发明的精髓。",
    price: 99.9,
    image: "necklace",
    category: "accessories",
    sales: 256,
    isNew: true
  },
  {
    id: 3,
    name: "墨枢纪念币",
    description: "以中国古代物理实验为主题，将历史与现代工艺完美结合。纪念币正面雕刻着古代科学家进行物理实验的场景。",
    price: 199.9,
    image: "coin",
    category: "collection",
    sales: 89,
    isNew: true
  },
  {
    id: 4,
    name: "墨枢T恤",
    description: "系列灵感源自中国古代伟大的物理实验与发明，将千年智慧与现代时尚完美融合。每一款T恤都精心印制了古代科学家的经典形象。",
    price: 79.9,
    image: "tshirt",
    category: "clothing",
    sales: 167,
    isNew: true
  },
  {
    id: 5,
    name: "墨枢徽章",
    description: "系列灵感源自中国古代伟大的物理实验与发明，将千年智慧与现代设计完美结合。每一枚徽章都精心刻画了古代科学家的经典形象。",
    price: 29.9,
    image: "badge",
    category: "accessories",
    sales: 312,
    isNew: true
  },
  {
    id: 6,
    name: "墨枢陶瓷马克杯",
    description: "系列灵感源自中国古代伟大的物理实验与发明，将千年智慧与现代生活完美结合。每一款马克杯都精心印制了古代科学家的经典形象。",
    price: 49.9,
    image: "mug",
    category: "daily",
    sales: 198,
    isNew: true
  },
  {
    id: 7,
    name: "墨枢鼠标垫",
    description: "系列灵感源自中国古代伟大的物理实验与发明，将千年智慧与现代办公生活完美结合。每一款鼠标垫都精心印制了古代科学家的经典形象。",
    price: 19.9,
    image: "mousepad",
    category: "daily",
    sales: 245,
    isNew: true
  },
  {
    id: 8,
    name: "墨枢抱枕",
    description: "拥抱智慧，品味经典！以中国古代物理实验为灵感，精致还原了古代科学家的风采。",
    price: 69.9,
    image: "pillow",
    category: "daily",
    sales: 134,
    isNew: true
  },
  {
    id: 9,
    name: "墨枢钥匙扣",
    description: "解锁智慧，传承经典！以中国古代物理实验为灵感，精致还原了古代智者的风采。",
    price: 24.9,
    image: "keychain",
    category: "accessories",
    sales: 289,
    isNew: true
  },
  {
    id: 10,
    name: "墨枢帆布包",
    description: "穿越时空，智慧随行！以中国古代物理实验为主题，简洁设计却充满文化韵味。",
    price: 89.9,
    image: "bag",
    category: "daily",
    sales: 156,
    isNew: true
  },
  {
    id: 11,
    name: "墨枢拼图",
    description: "探索古代智慧，感受物理之美。系列以中国古代物理实验为主题，精雕细琢，完美再现了古代科学家们的伟大成就。",
    price: 59.9,
    image: "puzzle",
    category: "collection",
    sales: 178,
    isNew: true
  },
  {
    id: 12,
    name: "墨枢·物理大家盲盒",
    description: "5款精美手办，随机发货，收集全套更有惊喜。每款手办代表一位古代物理学家。",
    price: 69.9,
    image: "blindbox",
    category: "collection",
    sales: 423,
    isNew: true
  }
];

const navigateToForum = () => {
  uni.navigateTo({
    url: "/pages/other/shop/creative",
  });
};
const pageSize = 10;
const currentPage = ref(1);
const loading = ref(false);
const hasMore = ref(true);
const prizeId = ref(1);
const filteredProducts = computed(() => {
  let products = store.products;

  // 如果不是"全部"分类，则进行分类筛选
  if (activeCategory.value !== "all") {
    products = products.filter((p) => p.category === activeCategory.value);
  }

  // 如果有搜索关键词，进行搜索筛选
  if (searchKey.value) {
    const searchTerm = searchKey.value.toLowerCase();
    products = products.filter((p) => {
      const name = String(p.name || '').toLowerCase();
      const description = String(p.description || '').toLowerCase();
      return name.includes(searchTerm) || description.includes(searchTerm);
    });
  }

  // 分页处理
  const start = 0;
  const end = currentPage.value * pageSize;

  // 确保返回所有符合条件的商品
  return products;
});

const onCategoryChange = (e) => {
  activeCategory.value = categories[e.currentIndex].value;
};

const selectedProduct = ref(null);
const selectedSpecIndex = ref(0);
const quantity = ref(1);

// 修改商品规格选项的计算属性
const currentSpecs = computed(() => {
  if (!selectedProduct.value) return [];

  // 通用规格
  const commonSpecs = {
    stationery: [
      { label: "A5", value: "a5" },
      { label: "A4", value: "a4" },
    ],
    accessories: [
      { label: "标准", value: "standard" },
      { label: "加长", value: "long" },
    ],
    clothing: [
      { label: "S", value: "s" },
      { label: "M", value: "m" },
      { label: "L", value: "l" },
      { label: "XL", value: "xl" },
    ],
    daily: [
      { label: "标准", value: "standard" },
      { label: "大号", value: "large" },
    ],
    collection: [
      { label: "单件", value: "single" },
      { label: "套装", value: "set" },
    ]
  };

  // 特殊商品规格
  const specialSpecs = {
    "墨枢笔记本": [
      { label: "A5", value: "a5" },
      { label: "A4", value: "a4" },
      { label: "B5", value: "b5" }
    ],
    "墨枢项链系列": [
      { label: "标准", value: "standard" },
      { label: "加长", value: "long" },
      { label: "定制", value: "custom" }
    ],
    "墨枢·物理大家盲盒": [
      { label: "单盒", value: "single" },
      { label: "整盒(5个)", value: "box" }
    ],
    "墨枢T恤": [
      { label: "S码", value: "s" },
      { label: "M码", value: "m" },
      { label: "L码", value: "l" },
      { label: "XL码", value: "xl" }
    ],
    "墨枢陶瓷马克杯": [
      { label: "350ml", value: "350ml" },
      { label: "450ml", value: "450ml" },
      { label: "定制款", value: "custom" }
    ],
    "墨枢抱枕": [
      { label: "40x40cm", value: "small" },
      { label: "45x45cm", value: "medium" },
      { label: "50x50cm", value: "large" }
    ],
    "墨枢帆布包": [
      { label: "小号", value: "small" },
      { label: "中号", value: "medium" },
      { label: "大号", value: "large" }
    ],
    "墨枢拼图": [
      { label: "300片", value: "300" },
      { label: "500片", value: "500" },
      { label: "1000片", value: "1000" }
    ]
  };

  // 先检查是否是特殊商品
  if (specialSpecs[selectedProduct.value.name]) {
    return specialSpecs[selectedProduct.value.name];
  }

  // 如果不是特殊商品，返回对应分类的通用规格
  return commonSpecs[selectedProduct.value.category] || [];
});

// 根据不同的商品ID设置不同数量的图片
const imageCountMap = {
  0: 5,  // 笔记本
  1: 4,  // 项链系列
  2: 4,  // 纪念币
  3: 4,  // T恤
  4: 4,  // 徽章
  5: 4,  // 马克杯
  6: 4,  // 鼠标垫
  7: 4,  // 抱枕
  8: 4,  // 钥匙扣
  9: 4,  // 帆布包
  10: 4, // 拼图
  11: 4, // 盲盒
  12: 1,
  13: 1,
  14: 1,
  16: 1,
  17: 1
};

// 显示规格选择弹窗
const showSpecsDialog = (product) => {
  selectedProduct.value = product;
  selectedSpecIndex.value = 0;
  quantity.value = 1;
  specsPopup.value.open();
};

// 关闭规格选择弹窗
const closeSpecsDialog = () => {
  specsPopup.value.close();
  selectedProduct.value = null;
};

// 规格选择变化
const onSpecChange = (e) => {
  selectedSpecIndex.value = e.currentIndex;
};

// 跳转到商品详情
const navigateToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/shop/detail?id=${id}`,
  });
};

const cartStore = useCartStore();

// 修改添加到购物车方法
const addToCart = () => {
  try {
    if (!selectedProduct.value) return;

    const cartItem = {
      id: selectedProduct.value.id,
      name: selectedProduct.value.name,
      price: selectedProduct.value.price,
      image: selectedProduct.value.image,
      quantity: quantity.value,
      specs: currentSpecs.value[selectedSpecIndex.value],
      category: selectedProduct.value.category,
    };

    cartStore.addToCart(cartItem);
    cartStore.saveToStorage(); // 保存到本地存储

    uni.showToast({
      title: "已添加到购物车",
      icon: "success",
    });

    closeSpecsDialog();
  } catch (error) {
    console.error('添加购物车失败:', error);
    uni.showToast({
      title: '添加失败，请重试',
      icon: 'error'
    });
  }
};

// 添加搜索建议逻辑
const suggestions = ref([]);

const onSearch = (value) => {
  if (!value) {
    suggestions.value = [];
    return;
  }
  // 根据输入筛选建议
  const searchTerm = String(value).toLowerCase();
  suggestions.value = store.nuo
    .filter((p) => {
      const name = String(p.name || '').toLowerCase();
      const description = String(p.description || '').toLowerCase();
      return name.includes(searchTerm) || description.includes(searchTerm);
    })
    .slice(0, 5);
};

const selectSuggestion = (item) => {
  searchKey.value = item.name;
  suggestions.value = [];
};

// 加载更多
const loadMore = async () => {
  if (loading.value || !hasMore.value) return;

  loading.value = true;

  // 模拟异步加载
  await new Promise((resolve) => setTimeout(resolve, 1000));

  const totalProducts = store.nuo.length;
  const currentTotal = currentPage.value * pageSize;

  if (currentTotal >= totalProducts) {
    hasMore.value = false;
  } else {
    currentPage.value++;
  }

  loading.value = false;
};

// 显示工具栏
const showToolbar = () => {
  toolbarPopup.value.open();
};



// 底部导航配置
const options = [
  {
    icon: "chat",
    text: "客服",
  },
  {
    icon: "shop",
    text: "店铺",
  },
  {
    icon: "cart",
    text: "购物车",
    info: 2,
  },
];

const buttonGroup = [
  {
    text: "加入购物车",
    backgroundColor: "#981f23",
    color: "#fff",
  },
];
const giftclick = () => {
  prizeId.value = 5;
};
// 图标点击事件
const onClick = (e) => {
  if (e.index === 2) {
    // 购物车图标
    uni.switchTab({
      url: "/pages/other/cart/index",
    });
  } else if (e.index === 1) {
    // 店铺图标
    uni.showToast({
      title: "进入店铺",
      icon: "none",
    });
  } else {
    // 客服图标
    uni.showToast({
      title: "联系客服",
      icon: "none",
    });
  }
};

// 按钮点击事件
const buttonClick = (e) => {
  if (e.index === 0) {
    showSpecsDialog(selectedProduct.value);
  }
};
</script>

<style scoped>
.shop-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

.search-section {
  
  padding: 20rpx;
  background-color: #fff;
}

.category-tabs {

  background: #fff;
  border-bottom: 1px solid #eee;
}

.tab-list {
  white-space: nowrap;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 20rpx;
}

.product-item {
  width: 100%;
}

.product-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  aspect-ratio: 1;
  overflow: hidden;
  
  cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.product-info {
  padding: 20rpx;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10rpx;
}

.product-name {
  font-size: 28rpx;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: #ff4d4f;
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin: 10rpx 0;
}



.sales-info {
  font-size: 24rpx;
  color: #999;
}

.cart-btn {
  padding: 0 !important;
  width: 60rpx !important;
  height: 60rpx !important;
  border-radius: 50% !important;
  display: flex !important;
  align-items: center;
  justify-content: center;
  
  
}

.specs-popup {
  max-height: 70vh;
  border-radius: 20rpx 20rpx 0 0;
}

.specs-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
}

.specs-body {
  max-height: calc(70vh - 300rpx);
  overflow-y: auto;
}

.logo {
  width: 80rpx;
  height: 80rpx;
}

.toolbar-popup {
  width: 300rpx;
  height: 100vh;
}

.toolbar-item {
  cursor: pointer;
}

.toolbar-item:hover {
  background-color: #f5f5f5;
}

.safe-area-bottom,
.action-bar,
.btn-danger {
  display: none;
}

.product-list {
  margin-bottom: 50px;
}

/* 添加自定义按钮样式 */
:deep(.uni-button) {
  background-color: var(--td-brand-color) !important;
  border-color: var(--td-brand-color) !important;
}

:deep(.uni-button--mini) {
  padding: 0 16rpx;
  font-size: 24rpx;
}

.close-btn {
  padding: 0 !important;
  min-width: 44rpx;
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}


</style>
